//
//  AddressVC.m
//  zhiche--delivery
//
//  Created by 王亚陆 on 16/5/10.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//

#import "CDAddressVC.h"
#import <Masonry.h>
#import "Header.h"
#import "Common.h"
#import "ActionSheetPicker.h"
#import "area.h"
#import "PlaceOrderVC.h"
#import "ChooseAddressVC.h"
#import "WKProgressHUD.h"
#import "CityDeliveryVC.h"
#import "QueryAddressVC.h"
#import "CDNewQueryAddressVC.h"
#import <AMapSearchKit/AMapSearchKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
#import "QueryAddressCell.h"
#import "CDAddressCell.h"
#import <ContactsUI/ContactsUI.h>
#import "CDAddressCityVC.h"


#define AreaBtnTag 100
#define KeepBtnTag 200
#define FieldTag 500
#define kMaxLength 5

#define MySetValue(dict, value) ((!dict[value] || [dict[value] isKindOfClass:[NSNull class]])?@"":dict[value])

@interface CDAddressVC ()<AMapSearchDelegate,CNContactPickerDelegate>
{
    UIImageView * nav;
    Common * Com;
    area * AREA;
    NSMutableDictionary * dic;
    WKProgressHUD *hud;
    
    UITableView * SearchTable;
    NSMutableArray * searchArr;
    UIView * searchBackView;
    NSString * limitCity;
    
}
@property (nonatomic,strong) CLLocationManager *manager;
@property (nonatomic,strong) UILabel *addressCH;
@property (nonatomic,strong) AMapSearchAPI * search;
@property (nonatomic,strong) AMapPOIKeywordsSearchRequest *request;
@property (nonatomic,strong) UIView * backView;
@property (nonatomic,strong) UIButton * AreaBtn;
@property (nonatomic,strong) UILabel * addressLabel;
@property (nonatomic,assign) BOOL store;


@end

@implementation CDAddressVC

- (instancetype)init

{
    self = [super init];
    if (self) {
        _dataSouce = [[NSMutableDictionary alloc]init];
        self.navtitle = [[NSString alloc]init];
        self.addresstype = [[NSString alloc]init];
        self.CityListCode = [[NSString alloc]init];
        self.CityListName = [[NSString alloc]init];
    }
    return self;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    
    limitCity = @"北京市";
    _manager = [[CLLocationManager alloc] init];
    _manager.delegate = self;
    // 请求授权，记得修改的infoplist，NSLocationAlwaysUsageDescription（描述）
    [_manager requestAlwaysAuthorization];
    
    
    self.view.backgroundColor = GrayColor;
    _backView = [[UIView alloc]init];
    _backView.backgroundColor = WhiteColor;
    [self.view addSubview:_backView];
    
    Com = [[Common alloc]init];
    AREA = [[area alloc]init];
    dic=[[NSMutableDictionary alloc]init];
    
    if ([_addresstype isEqualToString:@"1"]) {
        [dic setObject:@"1" forKey:@"addressType"]; //地址类型(0:发车地址，1:送达地址)
    }else if ([_addresstype isEqualToString:@"0"]){
        [dic setObject:@"0" forKey:@"addressType"]; //地址类型(0:发车地址，1:送达地址)
    }
    if ([_navtitle isEqualToString:@"1"]) {
        nav = [self createNav:@"收车地址编辑"];
    }else if ([_navtitle isEqualToString:@"0"]){
        nav = [self createNav:@"发车地址编辑"];
    }else{
        if ([_addresstype isEqualToString:@"1"]) {
            nav = [self createNav:@"新增收车地址"];
        }else{
            nav = [self createNav:@"新增发车地址"];
        }
    }
    [self.view addSubview:nav];
    [_backView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.top.mas_equalTo(nav.mas_bottom).with.offset(0);
        make.size.mas_equalTo(CGSizeMake(Main_Width, 43*3*kHeight));
        
    }];

    if (self.dataSouce[@"id"]) {
        [dic setObject:self.dataSouce[@"contact"] forKey:@"contact"];//联系人
        [dic setObject:self.dataSouce[@"phone"] forKey:@"phone"];//联系电话
        [dic setObject:self.dataSouce[@"isVeneer"] forKey:@"isVeneer"];//是否同城
        [dic setObject:self.dataSouce[@"id"] forKey:@"id"];//id
        
        [dic setObject:self.addresstype forKey:@"addressType"]; //地址类型
        
        NSMutableDictionary * address = [[NSMutableDictionary alloc]init];
        [address setObject:self.dataSouce[@"address"] forKey:@"address"];
        [address setObject:self.dataSouce[@"cityCode"] forKey:@"cityCode"];
        [address setObject:self.dataSouce[@"cityName"] forKey:@"cityName"];
        [address setObject:self.dataSouce[@"countyCode"] forKey:@"countyCode"];
        [address setObject:self.dataSouce[@"countyName"] forKey:@"countyName"];
        [address setObject:self.dataSouce[@"detailAddress"] forKey:@"detailAddress"];
        [address setObject:self.dataSouce[@"provinceCode"] forKey:@"provinceCode"];
        [address setObject:self.dataSouce[@"provinceName"] forKey:@"provinceName"];
        [address setObject:self.dataSouce[@"latitude"] forKey:@"latitude"];
        [address setObject:self.dataSouce[@"longitude"] forKey:@"longitude"];
        
        [dic setObject:address forKey:@"address"];
        
    }else{
        [dic setObject:@"" forKey:@"contact"];//联系人
        [dic setObject:@"" forKey:@"phone"]; //手机号
        [dic setObject:@"1" forKey:@"isVeneer"];//是否同城
        [dic setObject:self.addresstype forKey:@"addressType"]; //地址类型
    }
    
    [self createUI];
    
    searchArr = [[NSMutableArray alloc]init];
    
    searchBackView = [[UIView alloc]init];
    searchBackView.backgroundColor = GrayColor;
    searchBackView.hidden = YES;
    [self.view addSubview:searchBackView];
    [searchBackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.top.mas_equalTo(nav.mas_bottom).with.offset(0);
        make.size.mas_equalTo(CGSizeMake(Main_Width, Main_height-64));
    }];
    
    
    [AMapServices sharedServices].apiKey =@"decee6229c378085197d527b8a20e32f";
    self.search = [[AMapSearchAPI alloc] init];
    self.search.delegate = self;
    
    
    
    
    _addressCH = [Com createUIlabel:@"北京市" andFont:FontOfSize11 andColor:BtnTitleColor];
    [searchBackView addSubview:_addressCH];
    _addressCH.textAlignment = NSTextAlignmentCenter;
    [_addressCH mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(searchBackView.mas_left).with.offset(7*kWidth);
        make.top.mas_equalTo(searchBackView.mas_top).with.offset(18*kHeight);
        make.width.mas_equalTo(45*kWidth);
    }];
    
    UIImageView * imageRight = [[UIImageView alloc]init];
    imageRight.tag = 2000;
    imageRight.image = [UIImage imageNamed:@"common_list_arrows_more"];
    imageRight.transform = CGAffineTransformMakeRotation(M_PI_2);

    [searchBackView addSubview:imageRight];
    
    [imageRight mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(_addressCH.mas_right);
        make.size.mas_equalTo(CGSizeMake(5*kWidth, 7*kHeight));
        make.centerY.mas_equalTo(_addressCH.mas_centerY);
    }];
    
    
    UIButton * ChooseAddressBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [ChooseAddressBtn addTarget:self action:@selector(pressChooseAddressBtn:) forControlEvents:UIControlEventTouchUpInside];
    ChooseAddressBtn.selected = NO;
    //    btn.backgroundColor = [UIColor cyanColor];
    [searchBackView addSubview:ChooseAddressBtn];
    [ChooseAddressBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(searchBackView.mas_left);
        make.size.mas_equalTo(CGSizeMake(100*kWidth, 30*kHeight));
        make.centerY.mas_equalTo(_addressCH.mas_centerY);
    }];
    

    
    
    
    
    
    UITextField * field = [self createField:@"请输入详细地址" andFont:FontOfSize14];
    field.tag = 111111;
    [searchBackView addSubview:field];
    [field mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(imageRight.mas_right).with.offset(8*kWidth);
        make.centerY.mas_equalTo(_addressCH.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(Main_Width-120*kWidth, 30*kHeight));
    }];
    
    UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setTitle:@"取消" forState:UIControlStateNormal];
    [btn setTitleColor:BtnTitleColor forState:UIControlStateNormal];
    btn.titleLabel.font = Font(FontOfSize11);
    [btn addTarget:self action:@selector(pressCancel) forControlEvents:UIControlEventTouchUpInside];
    
    [searchBackView addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(field.mas_right);
        make.centerY.mas_equalTo(field.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(50*kWidth, 30*kHeight));
    }];
    
    
    
    SearchTable = [[UITableView alloc]initWithFrame:CGRectMake(0, 64*kHeight, Main_Width, 86*kHeight) style:UITableViewStylePlain];
    [SearchTable setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    SearchTable.delegate = self;
    SearchTable.dataSource = self;
    SearchTable.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    
    [searchBackView addSubview:SearchTable];
    [SearchTable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(searchBackView.mas_left);
        make.top.mas_equalTo(field.mas_bottom).with.offset(9*kHeight);
        make.size.mas_equalTo(CGSizeMake(Main_Width,Main_height-64-86*kHeight));
    }];
    [SearchTable reloadData];
    
}
-(void)pressChooseAddressBtn:(UIButton*)sender{
    
    

    
    CDAddressCityVC * addressCity = [[CDAddressCityVC alloc]init];
    
    [self.navigationController pushViewController:addressCity animated:YES];
    
    
    addressCity.callAddressCity = ^(NSString * AddressCity){
        
        _addressCH.text = AddressCity;
        limitCity = AddressCity;
    };
    
    
    //CD_addressListArea_Url
    
     
    NSLog(@"点击的是选择地址");
    
}

-(void)pressCancel{
    
    UITextField * field = (UITextField*)[self.view viewWithTag:111111];
    [field resignFirstResponder];
    [searchArr removeAllObjects];
    searchBackView.hidden = YES;
    

}


-(void)textsearchFieldWithText1:(UITextField*)field{
    
    //    [SearchTable mas_updateConstraints:^(MASConstraintMaker *make) {
    //
    //        make.height.mas_equalTo(searchBackView.frame.size.height-300*kHeight);
    //    }];
    
}

-(void)textsearchFieldWithText:(UITextField*)field{
    
    NSString * name1 = field.text;
    NSString *strUrl = [name1 stringByReplacingOccurrencesOfString:@" " withString:@""];
    searchBackView.hidden = NO;
    _request = [[AMapPOIKeywordsSearchRequest alloc] init];
    _request.keywords            = strUrl;
    _request.city                = limitCity;
    _request.cityLimit           = YES;
    _request.types      = @"";
    
    [self.search AMapPOIKeywordsSearch:_request];
}

- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response{
    
    [searchArr removeAllObjects];
    
    if (response.pois.count == 0)
    {
        [SearchTable reloadData];
        
        return;
    }else{
        
        for (AMapPOI *p in response.pois) {
            //把搜索结果存在数组
            
            //            NSLog(@"%@",p.address);
            
            [searchArr addObject:p];
        }
    }
    
    [SearchTable reloadData];
    
    //解析response获取POI信息，具体解析见 Demo
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *str=@"str";
    
    CDAddressCell * cell =  [tableView dequeueReusableCellWithIdentifier:str];
    
    if (cell ==nil) {
        
        cell = [[CDAddressCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str];
    }
    
    AMapPOI * p = searchArr[indexPath.row];
    NSLog(@"%@\n%@",p.name,p.address);
    cell.title.text = [NSString stringWithFormat:@"%@",p.name];
    cell.address.text = [NSString stringWithFormat:@"%@",p.address];
    return cell;
    
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return  searchArr.count;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 43*kHeight;
}



-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    AMapPOI * p = searchArr[indexPath.row];
    
    
    NSMutableDictionary * addressdic = [[NSMutableDictionary alloc]init];
    
    
    [addressdic setObject:p.name forKey:@"address"];
    [addressdic setObject:p.citycode forKey:@"cityCode"];
    [addressdic setObject:p.city forKey:@"cityName"];
    [addressdic setObject:p.province forKey:@"provinceName"];
    [addressdic setObject:p.pcode forKey:@"provinceCode"];
    [addressdic setObject:p.adcode forKey:@"countyCode"];
    [addressdic setObject:p.district forKey:@"countyName"];
    [addressdic setObject:p.address forKey:@"detailAddress"];
    [addressdic setObject:[NSString stringWithFormat:@"%f",p.location.latitude] forKey:@"latitude"];
    [addressdic setObject:[NSString stringWithFormat:@"%f",p.location.longitude] forKey:@"longitude"];
    
    [dic setObject:addressdic forKey:@"address"];
    
    //    NSLog(@"address%@cityName%@countyName%@provinceName%@detailAddress%@",addressdic[@"address"],addressdic[@"cityName"],addressdic[@"countyName"],addressdic[@"provinceName"],addressdic[@"detailAddress"]);
    
    _addressLabel.text = [NSString stringWithFormat:@"%@\n%@",addressdic[@"address"],addressdic[@"detailAddress"]];
    
    UITextField * field = (UITextField*)[self.view viewWithTag:111111];
    [field resignFirstResponder];
    [searchArr removeAllObjects];
    searchBackView.hidden = YES;
    
    
    
    
    NSLog(@"%@",_addressLabel.text);
    
    
}

-(void)createUI{
    NSArray * arrName = nil;
    NSArray * FieldName =nil;
    if ([_addresstype isEqualToString:@"0"]) {
        
        arrName = @[@"联系人",
                    @"手机号码",
                    @"详细地址"];
        FieldName = @[@"请输入联系人",
                      @"请输入联系电话",
                      @"",];
    }
    else{
        arrName = @[@"联系人",
                    @"手机号码",
                    @"详细地址"];
        FieldName = @[@"请输入联系人",
                      @"请输入联系电话"];
    }
    if (_dataSouce[@"id"]) {
        
        FieldName = @[self.dataSouce[@"contact"],self.dataSouce[@"phone"],self.dataSouce[@"address"]];
    }
    for (int i=0; i<arrName.count; i++) {
        UILabel * label = [self createUIlabel:arrName[i] andFont:FontOfSize14 andColor:fontGrayColor];
        [_backView addSubview:label];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_backView.mas_left).with.offset(18*kWidth);
            make.centerY.mas_equalTo(_backView.mas_top).with.offset(43*kHeight*i+21.5*kHeight);
        }];
        
        if (i==0) {
            UIImageView * RightImage =[[UIImageView alloc]init];
            RightImage.image = [UIImage imageNamed:@"common_list_arrows_more"];
            RightImage.tag = 1000;
            [_backView addSubview:RightImage];
            [RightImage mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.equalTo(_backView.mas_right).with.offset(-15*kWidth);
                make.centerY.mas_equalTo(label.mas_centerY);
                make.size.mas_equalTo(CGSizeMake(8*kWidth, 13*kHeight));
            }];
            
            UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
            [btn addTarget:self action:@selector(pressBtnNumber) forControlEvents:UIControlEventTouchUpInside];
            [_backView addSubview:btn];
            [btn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.equalTo(_backView.mas_right).with.offset(-15*kWidth);
                make.centerY.mas_equalTo(label.mas_centerY);
                make.size.mas_equalTo(CGSizeMake(40*kWidth, 30*kHeight));
            }];

            
            
            
        }
        
        
        
        if (arrName.count != i+1) {
            UIView * Hline =[[UIView alloc]init];
            Hline.backgroundColor = LineGrayColor;
            [_backView addSubview:Hline];
            [Hline mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(label.mas_left);
                make.bottom.mas_equalTo(_backView.mas_top).with.offset(43*kWidth*(i+1));
                make.size.mas_equalTo(CGSizeMake(Main_Width, 0.5));
            }];
        }
        if (_dataSouce[@"id"]) {
            
            if (i==0) {
                
                UITextField * field = [self createField:FieldName[i] andTag:FieldTag-1 andFont:FontOfSize14];
                field.placeholder = FieldName[i];
                [_backView addSubview:field];
                [field mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.left.equalTo(_backView.mas_left).with.offset(105*kWidth);
                    make.centerY.mas_equalTo(label.mas_centerY);
                    make.size.mas_equalTo(CGSizeMake(Main_Width/2, 25*kHeight));
                }];
            }
            
            if (i==1) {
                
                UITextField * field = [self createField:FieldName[i] andTag:FieldTag andFont:FontOfSize14];
                if (i==1) {
                    field.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
                }
                field.text = FieldName[i];
                field.placeholder = 0;
                [_backView addSubview:field];
                [field mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.left.equalTo(_backView.mas_left).with.offset(105*kWidth);
                    make.centerY.mas_equalTo(label.mas_centerY);
                    make.size.mas_equalTo(CGSizeMake(Main_Width/2, 25*kHeight));
                }];
            }
            
            
        }else{
            
            
            if (i==0) {
                
                UITextField * field = [self createField:FieldName[0] andTag:FieldTag-1 andFont:FontOfSize14];
                field.placeholder = FieldName[i];
                [_backView addSubview:field];
                [field mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.left.equalTo(_backView.mas_left).with.offset(105*kWidth);
                    make.centerY.mas_equalTo(label.mas_centerY);
                    make.size.mas_equalTo(CGSizeMake(Main_Width/2, 25*kHeight));
                }];
            }
            
            if (i==1) {
                
                UITextField * field = [self createField:FieldName[1] andTag:FieldTag andFont:FontOfSize14];
                if (i==1) {
                    field.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
                }
                [_backView addSubview:field];
                [field mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.left.equalTo(_backView.mas_left).with.offset(105*kWidth);
                    make.centerY.mas_equalTo(label.mas_centerY);
                    make.size.mas_equalTo(CGSizeMake(Main_Width/2, 25*kHeight));
                }];
            }
            
            
        }
        
        if (i ==2) {
            
            _addressLabel = [[UILabel alloc]init];
            
            if (_dataSouce[@"id"]) {
                _addressLabel.text = [NSString stringWithFormat:@"%@",_dataSouce[@"address"]];
            }else{
                _addressLabel.text = @"请输入详细地址";
                
            }
            _addressLabel.textColor = fontGrayColor;
            
            
            _addressLabel.numberOfLines = 2;
            _addressLabel.font = Font(FontOfSize10);
            [_backView addSubview:_addressLabel];
            
            _AreaBtn = [self createBtn:@"" andTag:AreaBtnTag];
            _AreaBtn.titleLabel.font = Font(FontOfSize12);
            [_AreaBtn addTarget:self action:@selector(pressBtnArea) forControlEvents:UIControlEventTouchUpInside];
            
            
            [_backView addSubview:_AreaBtn];
            [_AreaBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(_backView.mas_left).with.offset(105*kWidth);
                make.centerY.mas_equalTo(label.mas_centerY);
                make.size.mas_equalTo(CGSizeMake(Main_Width*0.75, 25*kHeight));
            }];
            [_addressLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(_AreaBtn.mas_left);
                make.centerY.mas_equalTo(label.mas_centerY);
                make.width.mas_equalTo(Main_Width*0.60);
                //                make.size.mas_equalTo(CGSizeMake(Main_Width*0.70, 25*kHeight));
            }];
            
            
            UIImageView * RightImage =[[UIImageView alloc]init];
            RightImage.image = [UIImage imageNamed:@"common_list_arrows_more"];
            RightImage.tag = 1000;
            [_backView addSubview:RightImage];
            [RightImage mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.equalTo(_backView.mas_right).with.offset(-15*kWidth);
                make.centerY.mas_equalTo(_AreaBtn.mas_centerY);
                make.size.mas_equalTo(CGSizeMake(8*kWidth, 13*kHeight));
            }];
        }
    }
    
    
    NSString *titleS ;
    if ([self.backString isEqualToString:@"1"]) {
        titleS = @"新增地址";
    } else {
        titleS = @"保存并使用";
        
    }
    
    
    
    UIButton * ConfirmBtn = [self createBtn:titleS andTag:KeepBtnTag];
    ConfirmBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    ConfirmBtn.titleLabel.font = Font(FontOfSize17);
    [ConfirmBtn setTitleColor:WhiteColor forState:UIControlStateNormal];
    [ConfirmBtn addTarget:self action:@selector(pressStoreBtn) forControlEvents:UIControlEventTouchUpInside];
    ConfirmBtn.backgroundColor = YellowColor;
    ConfirmBtn.layer.cornerRadius = 5;
    
    [self.view addSubview:ConfirmBtn];
    [ConfirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.size.mas_equalTo(CGSizeMake(293*kWidth, 40*kHeight));
        make.top.mas_equalTo(_backView.mas_bottom).with.offset(30*kHeight);
    }];
}

-(void)pressBtnNumber{
    
    
    //让用户给权限,没有的话会被拒的各位
    CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
    if (status == CNAuthorizationStatusNotDetermined) {
        CNContactStore *store = [[CNContactStore alloc] init];
        [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (error) {
                NSLog(@"weishouquan ");
            }else
            {
                NSLog(@"chenggong ");//用户给权限了
                CNContactPickerViewController * picker = [CNContactPickerViewController new];
                picker.delegate = self;
                picker.displayedPropertyKeys = @[CNContactPhoneNumbersKey];//只显示手机号
                [self presentViewController: picker  animated:YES completion:nil];
            }
        }];
    }
    
    if (status == CNAuthorizationStatusAuthorized) {//有权限时
        CNContactPickerViewController * picker = [CNContactPickerViewController new];
        picker.delegate = self;
        picker.displayedPropertyKeys = @[CNContactPhoneNumbersKey];
        [self presentViewController: picker  animated:YES completion:nil];
    }
    else{
        NSLog(@"您未开启通讯录权限,请前往设置中心开启");
    }

}
-(void)contactPicker:(CNContactPickerViewController *)picker didSelectContact:(CNContact *)contact{
    
    CNPhoneNumber * num = nil;
    NSString * name = nil;
    NSString * number = nil;

    if (contact.phoneNumbers.count >0) {
        num = contact.phoneNumbers[0].value;
        name = [NSString stringWithFormat:@"%@%@",contact.familyName,contact.givenName];
        number = [NSString stringWithFormat:@"%@",[num valueForKey:@"digits"]];
    }else{
        name = [NSString stringWithFormat:@"%@%@",contact.familyName,contact.givenName];
        number = @"";
    }
    
    
//    UITextField * field = [self createField:FieldName[i] andTag:FieldTag-1 andFont:FontOfSize14];

    UITextField * field0 = (UITextField*)[_backView viewWithTag:FieldTag -1];
    UITextField * field1 = (UITextField*)[_backView viewWithTag:FieldTag];
    field0.placeholder = name;
    field1.text = number;

    
    [dic setObject:name forKey:@"contact"];
    [dic setObject:number forKey:@"phone"];

//    NSLog(@"%@",contact);
    
}



-(void)pressBtnArea{
    
    UITextField * field = (UITextField*)[self.view viewWithTag:111111];
    field.text = @"";
    [searchArr removeAllObjects];
    [SearchTable reloadData];
    
    
    for (UITextField * field in _backView.subviews) {
        
        [field resignFirstResponder];
        
    }
    searchBackView.hidden = NO;
    

}


-(void)pressLiftBtn{
    
    UIImageView * image = (UIImageView*)[self.view viewWithTag:1000];
    image.transform = CGAffineTransformMakeRotation(0);
}




-(void)pressStoreBtn{
    
    __weak CDAddressVC * weekself = self;
    weekself.store = YES;
    
    
    NSString * phone = dic[@"phone"];
    NSString * contact = dic[@"contact"];
    NSString * name = nil;
    
    name = dic[@"address"][@"address"];
    
    NSMutableArray * arr = [[NSMutableArray alloc]init];
    [arr addObject:contact];
    [arr addObject:phone];
    [arr addObject:name];
    
    
    NSMutableArray * alertName = nil;
    if ([_addresstype isEqualToString:@"1"]) {
        alertName = @[@"您没有填写联系人",
                      @"您没有填写联系电话",
                      @"您没有填写详细地址"].mutableCopy;
        
    }
    else{
        alertName = @[@"您没有填写联系人",
                      @"您没有填写联系电话",
                      @"您没有填写详细地址"].mutableCopy;
        
    }
    
    for (int i = 0; i<arr.count; i++) {
        NSString * string = arr[i];
        if (string.length == 0) {
            weekself.store = NO;
            [self createUIAlertController:alertName[i]];
            break;
        }
    }
    
    NSString * url = nil;
    
    if (![self.navtitle isEqualToString:@"2"]) {
        
        url = CD_addressEdit_Url;
    }else{
        url = CD_addressAdd_Url;
    }
    if (weekself.store) {
        if([Common validateUserPhone:phone]){
            
            
            if (self.CityListName.length >0) {
                url =[NSString stringWithFormat:@"%@?isVeneer=1",url];
            }
            
            NSLog(@"%@",dic);
            
            NSMutableDictionary * addressInfro = dic[@"address"];
            NSData * jsonData = [NSJSONSerialization dataWithJSONObject:addressInfro options:NSJSONWritingPrettyPrinted error:nil];
            NSString * jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
            
            [dic setObject:jsonString forKey:@"address"];
            
            
            [Com afPostRequestWithUrlString:url parms:dic finishedBlock:^(id responseObj) {
                
                
                NSMutableDictionary * dicObj =[NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableContainers error:nil];
                
                if ([dicObj[@"success"] boolValue]) {
                    if(dicObj[@"data"] != nil){
                        hud = [WKProgressHUD popMessage:@"保存成功" inView:self.view duration:0.5 animated:YES];
                        
                        
                        //                        [addressdic setObject:p.name forKey:@"address"];
                        //                        [addressdic setObject:p.citycode forKey:@"cityCode"];
                        //                        [addressdic setObject:p.city forKey:@"cityName"];
                        //                        [addressdic setObject:p.province forKey:@"provinceName"];
                        //                        [addressdic setObject:p.pcode forKey:@"provinceCode"];
                        //                        [addressdic setObject:p.adcode forKey:@"countyCode"];
                        //                        [addressdic setObject:p.district forKey:@"countyName"];
                        //                        [addressdic setObject:p.address forKey:@"detailAddress"];
                        //                        [addressdic setObject:[NSString stringWithFormat:@"%f",p.location.latitude] forKey:@"latitude"];
                        //                        [addressdic setObject:[NSString stringWithFormat:@"%f",p.location.longitude] forKey:@"longitude"];
                        //
                        
                        
                        NSMutableDictionary * addressObject = [[NSMutableDictionary alloc]init];
                        
                        if ([_navtitle isEqualToString:@"1"] ||[_navtitle isEqualToString:@"0"]) {
                            addressObject[@"id"] = dic[@"id"];
                        }else{
                            addressObject[@"id"] = dicObj[@"data"];
                        }
                        //                        addressObject[@"address"] = dic[@"detailAddress"];
                        addressObject[@"address"] = addressInfro[@"address"];
                        addressObject[@"cityCode"] = addressInfro[@"cityCode"];
                        addressObject[@"cityName"] = addressInfro[@"cityName"];
                        addressObject[@"provinceCode"] = addressInfro[@"provinceCode"];
                        addressObject[@"provinceName"] = addressInfro[@"provinceName"];
                        addressObject[@"countyCode"] = addressInfro[@"countyCode"];
                        addressObject[@"countyName"] = addressInfro[@"countyName"];
                        
                        addressObject[@"phone"] = dic[@"phone"];
                        addressObject[@"contact"] = dic[@"contact"];
                        addressObject[@"addressType"] = dic[@"addressType"];
                       
                        if(dicObj[@"data"] != nil){
                            if( _callBackAddAddress){
                                _callBackAddAddress(addressObject, self.addresstype);
                            }
                            [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
                            
                            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                [hud dismiss:YES];
                                
                                
                                if (self.CityListName.length == 0) {
                                    
                                    if (![self.backString isEqualToString:@"1"]) {
                                        
                                        for (UIViewController *controller in self.navigationController.viewControllers) {
                                            if ([controller isKindOfClass:[PlaceOrderVC class]]) {
                                                [[NSNotificationCenter defaultCenter] postNotificationName:@"BackAddressDic" object:addressObject];
                                                
                                                [self.navigationController popToViewController:controller animated:YES];
                                            }
                                        }
                                        
                                    } else {
                                        [self.navigationController popViewControllerAnimated:YES];
                                    }
                                    
                                }else{
                                    
                                    if (![self.backString isEqualToString:@"1"]) {
                                        
                                        for (UIViewController *controller in self.navigationController.viewControllers) {
                                            if ([controller isKindOfClass:[CityDeliveryVC class]]) {
                                                [[NSNotificationCenter defaultCenter] postNotificationName:@"CityBackAddressDic" object:addressObject];
                                                
                                                [self.navigationController popToViewController:controller animated:YES];
                                            }
                                        }
                                        
                                    } else {
                                        [self.navigationController popViewControllerAnimated:YES];
                                    }
                                }
                            });
                        }
                    }else{
                        [self createUIAlertController:dicObj[@"message"]];
                    }
                }else{
                    [self createUIAlertController:dicObj[@"message"]];
                }
            } failedBlock:^(NSString *errorMsg) {
            }];
        }else{
            [self createUIAlertController:@"您输入的手机号有误"];
        }
    }
}

-(void)createBackUIAlertController:(NSString*)title{
    UIAlertController * alert =[UIAlertController alertControllerWithTitle:@"提示" message:title preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction * action =[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        for (UIViewController *controller in self.navigationController.viewControllers) {
            if ([controller isKindOfClass:[ChooseAddressVC class]]) {
                [self.navigationController popToViewController:controller animated:YES];
            }
        }
    }];
    UIAlertAction * action1 =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alert addAction:action1];
    [alert addAction:action];
    [self presentViewController:alert animated:YES completion:nil];
    
}

-(void)createUIAlertController:(NSString*)title

{
    UIAlertController * alert =[UIAlertController alertControllerWithTitle:@"提示" message:title preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction * action =[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction * action1 =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alert addAction:action1];
    [alert addAction:action];
    [self presentViewController:alert animated:YES completion:nil];
}

-(UILabel*)createUIlabel:(NSString *)title andFont:(CGFloat)font andColor:(UIColor *)color{
    
    UILabel * label =[[UILabel alloc]init];
    label.text = title;
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = color;
    UIFont *fnt = [UIFont fontWithName:@"HelveticaNeue" size:font];CGSize size = [label.text sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:fnt,NSFontAttributeName, nil]];
    CGFloat nameH = size.height;
    CGFloat nameW = size.width;
    label.textAlignment = NSTextAlignmentRight;
    label.frame =CGRectMake(0, 0, nameW, nameH);
    label.font = Font(font)
    return label;
}

-(UIButton*)createBtn:(NSString*)title andTag:(int)tag{
    
    UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setTitleColor:littleBlackColor forState:UIControlStateNormal];
    btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    btn.tag = tag;
    return btn;
}


-(void)textFieldWithText:(UITextField *)textField{
    //500 501 502 503
    UITextField * field = (UITextField*)textField;
    switch (textField.tag) {
        case 499://联系人
            
            //            [dic setObject:@"" forKey:@"contact"];//联系人
            //            [dic setObject:@"" forKey:@"phone"]; //手机号
            //            [dic setObject:@"" forKey:@"isVeneer"];//是否同城
            //            [dic setObject:@"" forKey:@"addressType"]; //地址类型
            
            
            if ([self textField:field shouldChangeCharactersInRange:NSMakeRange(0, 0) replacementString:@""]) {
                [dic setObject:field.text forKey:@"contact"];
            }
            break;
        case 500: //联系电话
            if ([self textField:field shouldChangeCharactersInRange:NSMakeRange(0, 0) replacementString:@""]) {
                [dic setObject:field.text forKey:@"phone"];
            }
            break;
            
            
            
        default:
            break;
    }
}

-(UITextField*)createField:(NSString*)placeholder andTag:(int)tag andFont:(double)font{
    UITextField * field =[[UITextField alloc]init];
    field.frame = CGRectMake(0, 0, Main_Width-91, 50);
    field.delegate = self;
    field.userInteractionEnabled = YES;
    field.textAlignment = NSTextAlignmentLeft;
    field.keyboardType = UIKeyboardTypeDefault;
    //    field.returnKeyType = UIReturnKeySend;
    field.tag = tag;
    field.placeholder =placeholder;
    //    field.text = placeholder;
    field.textColor = littleBlackColor;
    field.font =Font(font);
    [field addTarget:self action:@selector(textFieldWithText:) forControlEvents:UIControlEventEditingChanged];
    return field;
}


//触摸方法
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{
    for (UITextField * field in self.view.subviews) {
        [field resignFirstResponder];
    }
}
//点击return按钮 键盘隐藏 这是协议中的方法
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    //键盘隐藏 也就是让键盘取消第一响应者身份
    [textField resignFirstResponder];
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;
{  //string就是此时输入的那个字符textField就是此时正在输入的那个输入框返回YES就是可以改变输入框的值NO相反
    
    if ([string isEqualToString:@"\n"])  //按会车可以改变
    {
        return YES;
    }
    NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string]; //得到输入框的内容
    switch (textField.tag) {
        case 499://联系人
            if ([toBeString length] > 20) {
                textField.text = [toBeString substringToIndex:20];
                [self createUIAlertController:@"联系人输入不能超过20个字符"];
                return NO;
            }
            break;
        case 500: //联系电话
            
            if ([toBeString length] > 11) {
                textField.text = [toBeString substringToIndex:11];
                [self createUIAlertController:@"联系电话输入不能超过11个字符"];
                return NO;
            }
            break;
        case 501://
            if ([toBeString length] > 11) {
                textField.text = [toBeString substringToIndex:11];
                [self createUIAlertController:@"联系电话输入不能超过11个字符"];
                return NO;
            }
            break;
        case 502://详细地址
            if ([toBeString length] > 30) {
                textField.text = [toBeString substringToIndex:30];
                [self createUIAlertController:@"详细地址输入不能超过30个字符"];
                return NO;
            }
            break;
        default:
            break;
    }
    
    return YES;
}
-(UITextField*)createField:(NSString*)placeholder andFont:(double)font{
    
    UITextField * field =[[UITextField alloc]init];
    field.frame = CGRectMake(0, 0, Main_Width-120, 50);
    field.delegate = self;
    field.userInteractionEnabled = YES;
    field.textAlignment = NSTextAlignmentLeft;
    field.keyboardType = UIKeyboardTypeDefault;
    field.backgroundColor = WhiteColor;
    field.layer.cornerRadius = 5;
    field.layer.borderWidth = 0.5;
    field.layer.borderColor = WhiteColor.CGColor;
    
    UIImageView *accLeftView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon_search"]];
    accLeftView.frame = CGRectMake(20, 5, 24, 13);
    // 添加到左侧视图中
    field.leftView = accLeftView;
    field.leftViewMode = UITextFieldViewModeAlways; // 这句一定要加，否则不显示
    
    field.placeholder =placeholder;
    [field setFont:[UIFont fontWithName:@"STHeitiSC" size:font]];
    [field addTarget:self action:@selector(textsearchFieldWithText:) forControlEvents:UIControlEventEditingChanged];
    [field addTarget:self action:@selector(textsearchFieldWithText1:) forControlEvents:UIControlEventEditingDidBegin];
    
    [field placeholderRectForBounds:CGRectMake(100.0, 100.0, 100, 100)];
    
    return field;
}
#pragma mark - 代理方法，当授权改变时调用
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    
    
    // 获取授权后，通过
    if (status == kCLAuthorizationStatusAuthorizedAlways) {
        
        //开始定位(具体位置要通过代理获得)
        [_manager startUpdatingLocation];
        
        //设置精确度
        _manager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
        
        //设置过滤距离
        _manager.distanceFilter = 1000;
        
        //开始定位方向
//        [_manager startUpdatingHeading];
    }
    
    
}



#pragma mark - 定位代理
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    
    //    NSLog(@"%@",locations);
    
    //获取当前位置
    CLLocation *location = manager.location;
    //获取坐标
    CLLocationCoordinate2D corrdinate = location.coordinate;
    
    //打印地址
    NSLog(@"latitude = %f longtude = %f",corrdinate.latitude,corrdinate.longitude);
    
    // 地址的编码通过经纬度得到具体的地址
    CLGeocoder *gecoder = [[CLGeocoder alloc] init];
    
    [gecoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        
        CLPlacemark *placemark = [placemarks firstObject];
        
        //打印地址
        NSLog(@"%@",placemark.locality);
        limitCity = placemark.locality;
    }];
    
    //停止定位
    [_manager stopUpdatingLocation];
    
}






- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
@end
